function addFieldHandler() {
	$('#af_btn').click(function() {
		window.fields_cnt++;
		if($('#sf_btn').is(':hidden')) $('#sf_btn').show();
		$('div#newforms div.formcontain:first-child').clone()
		.appendTo('div#newforms')
		.find(':input').not(':submit, :button').val('');
		return false;
	});
}
function subtractFieldHandler() {
	$('#sf_btn').click(function() {
		window.fields_cnt--;
		if(window.fields_cnt <= 1) $(this).hide();
		$('div#newforms div.formcontain:last-child').remove();
		return false;
	});
}

function formIsValid() {
	// preliminaries
	window.form_errs = [];
	var email_regex = /^[^@]+@[^@]+\.[^@]+$/;
	var phone_regex = /\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4}/;
	var page = $('body').attr('class');
	
	// get to it
	if(page == 'createFarm') {
		var contact_email = $('input[name=contact_email]').get(0);
		var contact_phone = $('input[name=contact_phone]').get(0);
		var contact_mobile = $('input[name=contact_mobile]').get(0);
		if(!$.trim($('input[name=name]').val())) window.form_errs.push('Farm Name is required.');
		if(!$.trim($('input[name=contact_fn]').val())) window.form_errs.push('First Name is required.');
		if(!$.trim($('input[name=contact_ln]').val())) window.form_errs.push('Last Name is required.');
		if($.trim($(contact_email).val()) && !email_regex.test($(contact_email).val())) window.form_errs.push('Email is invalid.');
		if($.trim($(contact_phone).val()) && !phone_regex.test($(contact_phone).val())) window.form_errs.push('Phone is an invalid format.');
		if($.trim($(contact_mobile).val()) && !phone_regex.test($(contact_mobile).val())) window.form_errs.push('Mobile is an invalid format.');
		// check for empty field name
		$('input[name="field_name[]"]').each(function(idx) {
			if(!$.trim($(this).val())) {
				window.form_errs.push('Field Name is required for each field.');
				return false;
			}
		});
		// check for uniqueness of field name & field year
		$('input[name="field_name[]"]').each(function(i) {
			var current = this;
			var year = $(current).parent().parent().find('select[name="year[]"]').get(0);
			for(var j = i + 1; j < window.fields_cnt; j++) {
				var next = $('input[name="field_name[]"]').get(j);
				var next_year = $(next).parent().parent().find('select[name="year[]"]').get(0);
				if((next.value.toLowerCase() == current.value.toLowerCase()) && (next_year.value == year.value)) {
					window.form_errs.push('Field Name & Field Year must be unique for each field.');
					return false;
				}
			}
		});
		// optional numeric elements
		$('input[name="acres[]"]').each(function(idx) {
			if($.trim($(this).val()) && isNaN(parseInt($(this).val()))) {
				window.form_errs.push('Acres must be a positive integer.');
				return false;
			}
		});
		$('input[name="na_N[]"]').each(function(idx) {
			if($.trim($(this).val()) && isNaN(parseInt($(this).val()))) {
				window.form_errs.push('N must be a number.');
				return false;
			}
		});
		$('input[name="na_P[]"]').each(function(idx) {
			if($.trim($(this).val()) && isNaN(parseInt($(this).val()))) {
				window.form_errs.push('P must be a number.');
				return false;
			}
		});
		$('input[name="na_K[]"]').each(function(idx) {
			if($.trim($(this).val()) && isNaN(parseInt($(this).val()))) {
				window.form_errs.push('K must be a number.');
				return false;
			}
		});
		$('input[name="na_mN[]"]').each(function(idx) {
			if($.trim($(this).val()) && isNaN(parseInt($(this).val()))) {
				window.form_errs.push('mN must be a number.');
				return false;
			}
		});
		$('input[name="na_mP[]"]').each(function(idx) {
			if($.trim($(this).val()) && isNaN(parseInt($(this).val()))) {
				window.form_errs.push('mP must be a number.');
				return false;
			}
		});
		$('input[name="na_mK[]"]').each(function(idx) {
			if($.trim($(this).val()) && isNaN(parseInt($(this).val()))) {
				window.form_errs.push('mK must be a number.');
				return false;
			}
		});
		$('input[name="cc_rate[]"]').each(function(idx) {
			if($.trim($(this).val()) && isNaN(parseInt($(this).val()))) {
				window.form_errs.push('Cover Crop Rate must be a positive integer.');
				return false;
			}
		});
		$('input[name="cc_seed_cost[]"]').each(function(idx) {
			if($.trim($(this).val()) && isNaN(parseFloat(this.value.replace('$','').replace(',','')))) {
				window.form_errs.push('Seed Cost must be a dollar value.');
				return false;
			}
		});
		$('input[name="cc_sprayed[]"]').each(function(idx) {
			if($.trim($(this).val()) && isNaN(parseInt($(this).val()))) {
				window.form_errs.push('Cover Crop Spray Count must be an integer.');
				return false;
			}
		});
		$('input[name="cc_term_temp[]"]').each(function(idx) {
			if($.trim($(this).val()) && isNaN(parseFloat(this.value))) {
				window.form_errs.push('Termination Temp must be an integer.');
				return false;
			}
		});
		$('input[name="cc_yield[]"]').each(function(idx) {
			if($.trim($(this).val()) && isNaN(parseInt($(this).val()))) {
				window.form_errs.push('Cover Crop Yield must be a positive integer.');
				return false;
			}
		});
		$('input[name="ct_acres[]"]').each(function(idx) {
			if($.trim($(this).val()) && isNaN(parseInt($(this).val()))) {
				window.form_errs.push('Tillage Acres must be a positive integer.');
				return false;
			}
		});
	} else if(page == 'editFarm') {
		// no field data necessary
		var contact_email = $('input[name=contact_email]').get(0);
		var contact_phone = $('input[name=contact_phone]').get(0);
		var contact_mobile = $('input[name=contact_mobile]').get(0);
		if(!$.trim($('input[name=name]').val())) window.form_errs.push('Farm Name is required.');
		if(!$.trim($('input[name=contact_fn]').val())) window.form_errs.push('First Name is required.');
		if(!$.trim($('input[name=contact_ln]').val())) window.form_errs.push('Last Name is required.');
		if($.trim($(contact_email).val()) && !email_regex.test($(contact_email).val())) window.form_errs.push('Email is invalid.');
		if($.trim($(contact_phone).val()) && !phone_regex.test($(contact_phone).val())) window.form_errs.push('Phone is an invalid format.');
		if($.trim($(contact_mobile).val()) && !phone_regex.test($(contact_mobile).val())) window.form_errs.push('Mobile is an invalid format.');
	} else {
		// farm field (add or edit). no farm data necessary. remove [] from name attributes
		if(!$.trim($('input[name=field_name]').val())) window.form_errs.push('Field Name is required.');
		// optional numeric elements
		var acres = $('input[name=acres]').get(0);
		var na_N = $('input[name=na_N]').get(0);
		var na_P = $('input[name=na_P]').get(0);
		var na_K = $('input[name=na_K]').get(0);
		var na_mN = $('input[name=na_mN]').get(0);
		var na_mP = $('input[name=na_mP]').get(0);
		var na_mK = $('input[name=na_mK]').get(0);
		var cc_rate = $('input[name=cc_rate]').get(0);
		var cc_seed_cost = $('input[name=cc_seed_cost]').get(0);
		var cc_sprayed = $('input[name=cc_sprayed]').get(0);
		var cc_term_temp = $('input[name=cc_term_temp]').get(0);
		var cc_yield = $('input[name=cc_yield]').get(0);
		var ct_acres = $('input[name=ct_acres]').get(0);
		if($.trim($(acres).val()) && isNaN(parseInt($(acres).val()))) window.form_errs.push('Acres must be a positive integer.');
		if($.trim($(na_N).val()) && isNaN(parseInt($(na_N).val()))) window.form_errs.push('N must be a number.');
		if($.trim($(na_P).val()) && isNaN(parseInt($(na_P).val()))) window.form_errs.push('P must be a number.');
		if($.trim($(na_K).val()) && isNaN(parseInt($(na_K).val()))) window.form_errs.push('K must be a number.');
		if($.trim($(na_mN).val()) && isNaN(parseInt($(na_mN).val()))) window.form_errs.push('mN must be a number.');
		if($.trim($(na_mP).val()) && isNaN(parseInt($(na_mP).val()))) window.form_errs.push('mP must be a number.');
		if($.trim($(na_mK).val()) && isNaN(parseInt($(na_mK).val()))) window.form_errs.push('mK must be a number.');
		if($.trim($(cc_rate).val()) && isNaN(parseInt($(cc_rate).val()))) window.form_errs.push('Cover Crop Rate must be a positive integer.');
		if($.trim($(cc_seed_cost).val()) && isNaN(parseFloat(cc_seed_cost.value.replace('$','').replace(',','')))) window.form_errs.push('Seed Cost must be a dollar value.');
		if($.trim($(cc_sprayed).val()) && isNaN(parseInt($(cc_sprayed).val()))) window.form_errs.push('Cover Crop Spray Count must be an integer.');
		if($.trim($(cc_term_temp).val()) && isNaN(parseFloat($(cc_term_temp).val()))) window.form_errs.push('Termination Temp must be an integer.');
		if($.trim($(cc_yield).val()) && isNaN(parseInt($(cc_yield).val()))) window.form_errs.push('Cover Crop Yield must be a positive integer.');
		if($.trim($(ct_acres).val()) && isNaN(parseInt($(ct_acres).val()))) window.form_errs.push('Tillage Acres must be a positive integer.');
	}
	if(window.form_errs.length) return false;
	else return true;
}

function formSubmissionHandler() {
	$('#submit_btn').click(function() {
		// add validation here
		if(formIsValid()) {
			
			$('form#main_form').submit();
		} else {
			var err_msg = 'Error(s): \n\n';
			for(var i in window.form_errs) {
				var j = 1 + parseInt(i);
				err_msg += j + '. ' + window.form_errs[i] + '\n';
			}
			alert(err_msg);
		}
		return false;
	});
}

function addSearchAjax() {
  $('#srch_btn, #srch_all').click(function() {
    if(this.id == 'srch_btn' && !$.trim($('#q').val())) {
    	alert('The search box is empty.');
    	return false;
    } else if(this.id == 'srch_all') $('#srch_type').val('dump');
    else $('#srch_type').val('default');
    var form = $('#search form').get(0);
    var img_anchor = $('#search form').get(0);
    $.ajax({
      url: 			$(form).attr('action'),
      type: 		'GET',
      data: 		$(form).serialize(),
      cache:		false, // requests aren't cached by users browser
      dataType:		'html',
      beforeSend:	function() {
        $(img_anchor).css({'background-image' : 'url(/images/ajax-loader.gif)'});
      },// end beforeSend Handler
      success:		function(data, status, xhr) {
        $(img_anchor).css({'background-image' : 'url()'});
        $('#serps').html(data);
      }, // end success callback
      error:		function(xhr, status, error_thrown) {
    	$(img_anchor).css({'background-image' : 'url()'});
    	$('#serps').html("<div id='tech_prob'>Sorry, there has been an error: " + error_thrown + "</div>");
      }// end error callback
    });// end ajax
    return false;
  });// end click handler
}

function viewFieldHandler() {
	$('#fields_nav a').click(function() {
		$('#newforms .formcontain').addClass('hide');
		// could also do $.trim($(this).attr('class').replace('active',''))
		var id = '#' + $(this).attr('class').split(' ')[0];
		$(id).removeClass('hide');
		$('#fields_nav a.active').removeClass('active');
		$(this).addClass('active');
		// requires UI/Effects/Highlight library. Otherwise .animate() only expects numeric values, not hex
		$(id + ' td.fn, ' + id + ' td.fy').stop().css('background-color', '#FFFF99').animate({'background-color': '#F8F8FF'}, 2000);
		return false;
	});
}

$(document).ready(function() {
	//var height = parseInt($(window).height()) - 13;
	//$('#container').css('min-height', height + 'px');
	
	if($('#submit_btn').length) {
		formSubmissionHandler();
	}
	if($('#af_btn').length)  {
		window.fields_cnt = 1;
		$('#sf_btn').hide();
		addFieldHandler();
		subtractFieldHandler();
	}
	if($('#search').length) {
		addSearchAjax();
	}
	if($('#fields_nav').length) {
		viewFieldHandler();
	}
});